<?php

namespace app\admin\controller;

use app\admin\model\ImageZoneModel;
use app\admin\model\UserModel;
use app\admin\utils\cosOper;
use app\admin\utils\jsonResult;
use app\admin\utils\ontimeLog;
use think\Config;
use think\Controller;
use think\Exception;
use think\Request;
use think\Db;


class ImageZone extends Controller
{

    public function _initialize()
    {

    }

    /**********视图模板***********/

    public function image_list()
    {
        $page = input('param.page');
        $limit = input('param.limit');
        $imageZoneModel = new ImageZoneModel();

        $imageList = $imageZoneModel->list($page, $limit);

        return $this->fetch('image_list', ['imageList' => $imageList]);
    }

    public function image_upload()
    {
        return $this->fetch();
    }

    /**********JsonAPI接口***********/
    public function getImageList(): \think\response\Json
    {
        $page = input('param.page');
        $limit = input('param.limit');
        $imageZoneModel = new ImageZoneModel();
        return (new jsonResult)::result(0, "获取图片列表成功", $imageZoneModel->list($page, $limit));
    }

    public function uploadImage(Request $request): \think\response\Json
    {
        if (!$this->request->isPost()) {
            return (new jsonResult)::result(501, "上传失败 Post请求中的文件无效");
        }

        $files = $this->request->file();
        foreach ($files as $file) {
            if (empty($file)) {
                return (new jsonResult)::result(501, "上传失败 Post请求中的文件无效", ['file' => $file]);
            }

            //获取上传文件信息
            $imgPath = ROOT_PATH . DS . 'uploads';
            $info = $file->move($imgPath);

            if (!$info) {
                ontimeLog::mylog("上传文件失败，错误信息：" . $file->getError(), __FILE__, __METHOD__);
                return (new jsonResult)::result(501, "上传失败 服务器错误");
            }

            //上传到COS和数据库
            $saveName = $info->getSaveName();
            if ((new cosOper())->uploadObj($imgPath . DS . $saveName, Config::get('cos.product_key') . '/' . $saveName)) {

                $fileMd5 = explode('.', $info->getFilename())[0];
                $data = [
                    'img_url' => Config::get('cos.url_pre') . '/' . Config::get('cos.product_key') . '/' . $saveName,
                    'key' => '/' . Config::get('cos.product_key') . '/' . $saveName,
                    'md5' => $fileMd5,
                    'img_comment' => "",
                    'add_time' => date('Y-m-d h:i:s', time()),
                ];
                (new ImageZoneModel())->add($data);
                ontimeLog::mylog("文件上传成功：" . $info->getSaveName(), __FILE__, __METHOD__);
                return (new jsonResult)::result(0, "上传成功", ['src' => $data['img_url']]);

            } else {
                return (new jsonResult)::result(501, "上传到COS失败");
            }
        }

        return (new jsonResult)::result(501, "上传失败 不是合法的Post请求");
    }


    public function deleteImageByMd5(Request $request): \think\response\Json
    {
        $md5 = $request->param('md5');
        $imageZoneModel = new ImageZoneModel();
        Db::startTrans();
        try {
            $objKey = $imageZoneModel->selectByMd5($md5)['key'];
            ontimeLog::mylog("objKey：" . $objKey, __FILE__, __METHOD__);
            $deleteRes = $imageZoneModel->delete($md5) == 1;
            ontimeLog::mylog("deleteRes：" . $deleteRes, __FILE__, __METHOD__);
            if ($deleteRes) {
//                $cosOper = new cosOper();
//                if ($objKey != -1 && $cosOper->deleteObj($objKey)) {
                Db::commit();
                ontimeLog::mylog("COS对象删除成功：" . $md5, __FILE__, __METHOD__);
                return (new jsonResult)::result(200, "删除成功");
//                } else {
//                    Db::rollback();
//                    return (new jsonResult)::result(501, "删除失败 桶中未找到该数据");
//                }
            }
        } catch (\Exception $e) {
            Db::rollback();
            ontimeLog::mylog('删除失败：' . $e, __FILE__, __METHOD__);
            return (new jsonResult)::result(501, "删除失败：" . $e);
        }
        return (new jsonResult)::result(501, "删除失败");
    }

}
